package scanner.impl;

import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import pojo.Customer;
import scanner.DataScanner;

public class DataScannerImpl implements DataScanner {
	private InputStream in;
	private Scanner scaner;

	// /生日
	private static final String BIRTHDAY = "((19\\d{2})|(20((0\\d)|(1[0-7]))))(-|\\/)((0?[1-9])|(1?\\d))\\7(([0-2]?\\d)|(3[0-1]))";

	private static final String EMAIL = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";

	// 数字
	private static final String NUMBERS = "^\\d+$";
	// /姓名
	private static final String NAME = "(\\w+|[\\u4e00-\\u9fa5]+)";
	// /性别
	private static final String SEX = "([tT]rue|[Ff]alse)";

	public DataScannerImpl(InputStream in) {
		super();
		this.in = in;
		scaner = new Scanner(in);
	}

	public List<Customer> scann() {
		List<String> list = preScan("regexpr");
		List<Customer> list1 = new ArrayList<Customer>();
		String reg = "\\s+";
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		for (String s : list) {
			// System.out.println("处理成Customer 之前， s : " + s);
			String[] ss = s.split(reg);

			// /在这一步就应该开始判断了，不然，构造不出Customer

			if (!(ss[0] + "").matches(NUMBERS))
				continue;
			if (!(ss[1].matches(NAME)))
				continue;
			if (!(ss[2].matches(EMAIL)))
				continue;
			if (!(ss[3].matches(SEX)))
				continue;
			if (!(ss[4].matches(BIRTHDAY)))
				continue;

			Customer c = new Customer();
			c.setId(Integer.valueOf(ss[0]));
			c.setName(ss[1]);
			c.setEmail(ss[2]);
			c.setSex((ss[3].length() == 4) ? true : false);
			try {
				String birth = ss[4].replaceAll("[\\/]", "-");
				c.setBirth(dateFormat.parse(ss[4]));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			list1.add(c);
		}
		return list1;
	}

	
	
	private List<String> preScan(String reg) {
		List<String> list = new ArrayList<String>();
		while (scaner.hasNext()) {
			list.add(scaner.nextLine());
		}
		return list;
	}

}
